package com.zonski.jbots.desktop.editer.tool;

import com.zonski.jbots.desktop.editer.AbstractMouseTool;
import com.zonski.jbots.engine.Entity;
import com.zonski.jbots.engine.Rectangle;
import com.zonski.jbots.game.EntityHelper;

import java.awt.event.MouseListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

/**
 * Created by IntelliJ IDEA.
 * User: Chris Glover
 * Date: Oct 27, 2003
 * Time: 4:08:39 PM
 * To change this template use Options | File Templates.
 */
public class MoveTool extends AbstractMouseTool
{
    private MoveMouseListener mouseListener;

    public MoveTool()
    {

    }

    protected MouseListener createMouseListener()
    {
        if(this.mouseListener == null)
        {
             this.mouseListener = new MoveMouseListener();
        }
        return this.mouseListener;
    }

    protected MouseMotionListener createMouseMotionListener()
    {
        if(this.mouseListener == null)
        {
             this.mouseListener = new MoveMouseListener();
        }
        return this.mouseListener;
    }

    private class MoveMouseListener extends MouseAdapter implements MouseMotionListener
    {
        private Entity draggedEntity;
        private int xoff;
        private int yoff;

        public void mousePressed(MouseEvent event)
        {
            // find the entity being clicked upon
            this.draggedEntity = getContext().getEntityAt(event.getX(), event.getY());
            if(draggedEntity != null)
            {
                Rectangle bounds = draggedEntity.bounds;
                xoff = event.getX() - bounds.x;
                yoff = event.getY() - bounds.y;
            }
        }

        public void mouseReleased(MouseEvent event)
        {
            if(this.draggedEntity != null && getContext().isCentredOnTile())
            {
                Rectangle bounds = this.draggedEntity.bounds;
                EntityHelper.centreAtClosestTile(bounds, bounds, getContext().getRoom());
                getContext().getComponent().repaint();
            }
            this.draggedEntity = null;
        }

        public void mouseDragged(MouseEvent event)
        {
            if(this.draggedEntity != null)
            {
                Rectangle bounds = this.draggedEntity.bounds;
                bounds.x = event.getX() - xoff;
                bounds.y = event.getY() - yoff;
                getContext().getComponent().repaint();
            }
        }

        public void mouseMoved(MouseEvent event)
        {
        }
    }
}
